import {Component} from '@angular/core';
import {AlertController, App, IonicPage, NavController} from 'ionic-angular';
import {PublicService} from "../../common/public.service";
import {HttpService} from "../../providers/HttpService";
import {DOWNLOAD_APP_URL, GET_VERSION_URL, LOGIN_URL} from "../../providers/Constants";
import {File} from '@ionic-native/file';
import {FileTransfer, FileTransferObject} from "@ionic-native/file-transfer";
import {FileOpener} from "@ionic-native/file-opener";

/**
 * 登录应用
 * auther hjg
 * time 20180607
 */

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  version: string = "1.0.0";

  userCode: string;
  password: string;

  constructor(public navCtrl: NavController,
              public pub: PublicService,
              public app: App,
              public http: HttpService,
              private transfer: FileTransfer,
              private file: File,
              private fileOpener: FileOpener,
              private alertCtrl: AlertController) {
  }

  ionViewDidLoad() {
    localStorage.setItem("mpower-version", this.version);
    if (localStorage.getItem("mpower-userCode")) {
      this.userCode = localStorage.getItem("mpower-userCode");
    }
    if (localStorage.getItem("mpower-password")) {
      this.password = localStorage.getItem("mpower-password");
    }
  }


  /**
   *登录
   * @param username
   * @param password
   */
  logIn() {
    if (!this.userCode) {
      this.pub.presentLoadingToast("请输入工号");
    } else if (!this.password) {
      this.pub.presentLoadingToast("请输入密码");
    } else {
      let params = {
        "username": this.userCode.trim(),
        "password": this.password.trim()
      };
      this.http.get(SERVER_URL + LOGIN_URL, '&', params, true).then(res => {
        if (res.success) {
          sessionStorage.setItem("session", res.data.sessionId);
          sessionStorage.setItem("fdNowDate", res.data.fdNowDate);
          localStorage.setItem("mpower-userCode", this.userCode.trim());
          localStorage.setItem("mpower-password", this.password.trim());
          localStorage.setItem("mpower-personName",  res.data.personName);
          this.navCtrl.push("TabsPage");
          this.cleanStorage();
          this.getVersion();
        } else {
          this.pub.presentLoadingToast(res.msg);
        }
      });
    }
  }

  /**
   * 清理session
   */
  cleanStorage() {
    sessionStorage.removeItem("defaultHandleType");
    sessionStorage.removeItem("defaultProduct");
    sessionStorage.removeItem("defaultAttendanceType");
    sessionStorage.removeItem("defaultProductSeries");
  }


  /**
   * 获取当前系统最新版本
   */
  public getVersion() {
    let params = {
      "platform": "android",
      "currVersion": this.version,
      "appCode": "dlo",
      "sessionid": sessionStorage.getItem("session")
    };
    this.http.get(SERVER_URL + GET_VERSION_URL, "&", params, false).then(res => {
      if (res.msgCode == '0001') {
        //有更新
        if (res.update == 'Y') {
          if (res.force == 'Y') {
            let alert = this.alertCtrl.create({
              title: '提示',
              subTitle: "有新版本" + res.version + "，请更新！",
              buttons: [{
                text: '确定',
                handler: () => {
                  this.downloadApp(SERVER_URL + DOWNLOAD_APP_URL, "synear_" + res.version, res.attachmentId, alert);
                }
              }]
            });
            alert.present();
          } else {
            let alert = this.alertCtrl.create({
              title: '提示',
              subTitle: "有新版本" + res.version + "，现在更新吗？",
              buttons: [{text: '取消'},
                {
                  text: '确定',
                  handler: () => {
                    this.downloadApp(SERVER_URL + DOWNLOAD_APP_URL, "synear_" + res.version, res.attachmentId, alert);
                  }
                }]
            });
            alert.present();
          }
        }
      } else {
        this.pub.presentLoadingToast(res.msgDesc);
      }
    });
  }


  /**
   * 下载APP
   */
  downloadApp(url: string, version: string, attachmentid: string, alert: any) {
    const fileTransfer: FileTransferObject = this.transfer.create();
    const apk = this.file.dataDirectory + "/" + version + ".apk";
    fileTransfer.download(url + "&attachmentid=" + attachmentid, apk).then((entry) => {
      this.fileOpener.open(apk, 'application/vnd.android.package-archive').then(() => {
        if (alert) {
          alert.dismiss();
        }
      });
    }, (e) => {
      console.error(e.exception);
      alert(e.exception);
    });

    if (alert) {
      alert.dismiss();
    }

    alert = this.alertCtrl.create({
      title: '下载进度：0%',
      enableBackdropDismiss: false,
      //buttons: ['后台下载']
    });
    alert.present();
    fileTransfer.onProgress((event: ProgressEvent) => {
      let num = Math.floor(event.loaded / event.total * 100);
      /*if (num === 100) {*/
      if (alert && num > 99) {
        alert.dismiss();
      } else {
        let title = document.getElementsByClassName('alert-title')[0];
        title && (title.innerHTML = '下载进度：' + num + '%');
        if (alert && num > 99) {
          alert.dismiss();
        }
      }
    });
  }
}
